﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using TeamWork_Server.HTTP;
using Newtonsoft.Json;

namespace TeamWork_Server
{
    public class CodeUpdateService
    {
        public CodeUpdateService()
        {
        }

        private string RemoveControlCharacters(string inString)
        {
            if (inString == null) return null;

            StringBuilder newString = new StringBuilder();
            char ch;

            for (int i = 0; i < inString.Length; i++)
            {

                ch = inString[i];

                if (!char.IsControl(ch))
                {
                    newString.Append(ch);
                }
            }
            return newString.ToString();
        }

        private List<twlib.CodeUpdateTemplate> CodeUpdates = new List<twlib.CodeUpdateTemplate>();

        public void service_HttpContextReceived(object sender, HttpContextReceivedEventArgs e)
        {
            if (e.Context.Request.Headers["packet_type"] == "CodeSubmit")
            {
                BinaryReader reader = new BinaryReader(e.Context.Request.InputStream);
                twlib.CodeUpdateTemplate temp = new twlib.CodeUpdateTemplate();
                temp.Author = reader.ReadString();
                temp.Date = reader.ReadInt64();
                temp.File = reader.ReadString();
                temp.Code = reader.ReadString();

                CodeUpdates.Add(temp);

                Log.Info("Received a new code update for file '" + temp.File + "'.");
                ChatService.BroadcastMessage("[SERVER]: Received a new code update for file '" + temp.File + "', from: " + temp.Author + ".");
                e.Context.Response.Close();
            }
            if (e.Context.Request.Headers["packet_type"] == "CodeReview")
            {
               string fName = e.Context.Request.Headers["file_name"];
               Log.Info("Sending modification entries for file " + fName);
               var updates = from c in CodeUpdates.ToArray() where c.File == fName orderby c.Date select c;
               BinaryWriter writer = new BinaryWriter(e.Context.Response.OutputStream);
               writer.Write(updates.Count());
                foreach(var v in updates)
                {
                    writer.Write(v.Author);
                    writer.Write(v.Date);
                    writer.Write(v.File);
                    writer.Write(v.Code);
                }
                writer.Flush();
                e.Context.Response.Close();

            }
        }
    }
}
